import {
  definePage,
  udp,
  OType,
  Layout,
  getCurrentWindow,
} from '@cscec/udp-ui';
import { ToastComponent, render as renderAmis } from 'amis';
import React, { useMemo } from 'react';
import { Empty } from 'antd';
import { getAmisEnv } from '@/components/editor/util';
import { BaseCustom } from '../BaseCustom';
import { commonConfig, QueryParamName } from '../constVar';
import { initPage, PageContext, usePageCtx } from '../context';
import type {
  IListPage, IListPageRef, IPageFunction, IPageListProps,
} from '../interface';
import initListController from './controller';
import listModel from './store';

const typeName = {
  [OType.Add]: '新增', [OType.Edit]: '编辑', [OType.View]: '查看', [OType.WorkFlow]: '工作流',
};

const PageListView: React.FC<IPageListProps> = () => {
  const { page, capacity, microServiceName, uiInfo } = usePageCtx<IListPage>();
  const urlRoot = page.getMicroServiceName();

  const env = useMemo(() => getAmisEnv('render', { urlRoot }), [urlRoot]);

  return (
    <Layout loading={page.props.loading.global}>
      <ToastComponent key="toast" position="top-right" />
      {
        uiInfo ? renderAmis(uiInfo, {
          scopeRef(amisScoped: any) { getCurrentWindow().amisScoped = amisScoped; },
          style: { height: '100%' },
          className: 'lowcode-view-root',
          extraData:{
            capacity,
            microServiceName,
            page,
          }
        }, env) : <Empty style={{ marginTop: 100 }} />
      }
    </Layout>
  );
};

function CustomFormList({ busType: defaultBusType, nextRoute = '/customform/detail' }: IPageFunction) {
  const { busType } = initPage(defaultBusType);
  const InnerPage = useMemo(
    () => definePage({
      ...commonConfig,
      model: listModel({ busType }),
      component: class extends BaseCustom<IListPageRef, IListPage> {
        constructor(props: any) {
          super(props, nextRoute, true);
          initListController(this as any);
        }

        /**
           * 在page实例下面提供统一的打开明细方法
           * @param oType 页面打开类型
           * @param record 当前选择数据行记录
           */
        async openDetail(oType: OType = OType.Add, record?: { [x: string]: any; }, otherQuery?: { [x: string]: any; }) {
          const appTitle = udp.getQueryValue(QueryParamName.appTitle);
          const preview = udp.getQueryValue('preview');
          // 获取内置钩子
          const defaultParams: any = {
            [QueryParamName.oType]: oType,
            [QueryParamName.busType]: busType,
            ...otherQuery
          };
          if (appTitle) {
            defaultParams[QueryParamName.appTitle] = `${appTitle}-${typeName[oType]}`;
          }
          // 如果是预览过来，需要带上预览id
          if (preview) {
            defaultParams.preview = preview;
          }
          const hooks = await this.createHooks();
          const hookReturn = await hooks.transferDetailPageURL?.({ oType, record, defaultParams });
          if (hookReturn?.cancel) {
            return;
          }
          if (record) {
            udp.open(this.nextRoute, {
              [QueryParamName.id]: record[this.getBusKey()],
              creator: record.insert_user_no,
              ...defaultParams,
              ...hookReturn?.params,
            });
          } else {
            udp.open(this.nextRoute, {
              ...defaultParams,
              ...hookReturn?.params,
            });
          }
        }

        async refreshList() {
          await this.getCmpApi(this.getPublicProperty().masterTableName)?.refreshData();
        }

        /**
           * 获取选中记录
           */
        getSelectedRecord() {
          return this.getCmpApi(this.getPublicProperty().masterTableName)?.getSelectedData() || [];
        }

        /**
           * 获取当前选中行记录，没选中提示错误
           */
        async getCurrentRecord() {
          const selectedRecord = this.getSelectedRecord();
          if (!selectedRecord.length) {
            await udp.alert('请先选择数据行');
            return;
          }
          return selectedRecord[0];
        }

        componentDidMount(): void {
          // 注册列表回刷事件
          this.unList.push(
            udp.onRefreshList(this.busType, () => {
              this.refreshList().then();
            }),
          );
        }

        render() {
          return (
            <PageContext.Provider value={this.state.providerValue}>
              <PageListView />
            </PageContext.Provider>
          );
        }
      },
    }),
    [busType],
  );

  return <InnerPage />;
}

export default function () {
  return <CustomFormList />;
}
